import { Inject, Injectable, OnDestroy } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { OverlayContainer } from '@angular/cdk/overlay';
import { Platform } from '@angular/cdk/platform';

// origin version: https://github.com/angular/components/blob/036729dc1a7b41236fcda9b23c578f9ef65b484c/src/cdk/overlay/overlay-container.ts
@Injectable({providedIn: 'root'})
export class fuiOverlayContainer extends OverlayContainer implements OnDestroy {
  constructor(
    @Inject(DOCUMENT) _document: any,
    protected platform: Platform,
  ) {
    super(_document, platform);
  }

  getContainerElement(): HTMLElement {
    this.setContainerElement();
    return this._containerElement;
  }

  setContainerElement() {
    const containerClass = 'cdk-overlay-container';
    const previousContainers = this._document.getElementsByClassName(containerClass);

    // 如果有超过一个的overlay container 那么只留一个
    if (previousContainers && previousContainers.length) {
      for (let i = 1; i < previousContainers.length; i++) {
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        previousContainers[i].parentNode!.removeChild(previousContainers[i]);
      }
    }

    // 如果当前实例中_containerElement为空
    if (previousContainers.length && !this._containerElement) {
      this._containerElement = previousContainers[0] as HTMLElement;
    }

    // 如果之前没有cdk-coverlay-container
    if (!previousContainers || !previousContainers.length) {
      const container = this._document.createElement('div');
      container.classList.add(containerClass);
      this._document.body.appendChild(container);
      this._containerElement = container;
    }
  }

  // 此处不销毁_containerElement
  ngOnDestroy() {
  }
}
